package com.ywu.bpmn.flow.consumer.process;

import com.ywu.bpmn.flow.consumer.YwuFlowConsumer;
import com.ywu.bpmn.flow.data.YwuFlowInstanceRepository;
import com.ywu.bpmn.flow.entity.YwuFlowInstanceEntity;
import com.ywu.bpmn.flow.entity.YwuFlowTaskEntity;
import com.ywu.bpmn.spi.dto.YwuBpmnMqDto;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.utils.TimerIdGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName YwuFlowTaskCreateConsumer
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/4/23 20:55
 * @Version 1.0
 **/
@Component
@Slf4j
public class YwuFlowTaskCreateConsumer implements YwuFlowConsumer {

    @Autowired
    private YwuFlowInstanceRepository repository;

    private static final String TASK_CREATE = "task-create";

    @Override
    public String type() {
        return TASK_CREATE;
    }

    @Override
    public void process(String key, String value) {
        log.debug("do consumer task create");
        // 将json串反序列化
        YwuBpmnMqDto deserialize = GsonUtils.deserialize(value, YwuBpmnMqDto.class);
        // 插入一条审批结点记录，状态为审批中 - RUNNING
        YwuFlowTaskEntity ywuFlowTaskEntity = new YwuFlowTaskEntity();
        ywuFlowTaskEntity.setId(TimerIdGenerateUtil.nextId());
        ywuFlowTaskEntity.setTaskId(deserialize.getTaskId());
        ywuFlowTaskEntity.setFlowNodeId(deserialize.getNodeId());
        ywuFlowTaskEntity.setFlowInstanceId(deserialize.getInstanceId());
        ywuFlowTaskEntity.setAssignee(deserialize.getAssignee());
        ywuFlowTaskEntity.setStatus(YwuFlowTaskEntity.RUNNING_STATUS);
        ywuFlowTaskEntity.createInfo(deserialize.getAssignee());
        YwuFlowInstanceEntity ywuFlowInstanceEntity = new YwuFlowInstanceEntity();
        ywuFlowInstanceEntity.setId(deserialize.getInstanceId());
        YwuFlowInstanceEntity instanceById = repository.getInstanceById(ywuFlowInstanceEntity);
        ywuFlowTaskEntity.setTenantId(instanceById.getTenantId());
        repository.insertTask(ywuFlowTaskEntity);
        // 修改流程实例当前结点
        YwuFlowInstanceEntity updateCurrentNode = new YwuFlowInstanceEntity();
        updateCurrentNode.setId(deserialize.getInstanceId());
        updateCurrentNode.setCurrentNode(ywuFlowTaskEntity.getFlowNodeId());
        updateCurrentNode.updateInfo(ywuFlowTaskEntity.getAssignee());
        repository.updateCurrentNode(updateCurrentNode);
    }
}
